<script lang="ts" setup>
import type { TabsPaneContext } from 'element-plus'
import { getImageCaptcha, getSmsCaptchaByPhone, loginSubmit } from '@/api/login'
import router from '@/router/index'
import { getQueryString } from '@/utils/globalUtils'
import { Lock, User } from '@element-plus/icons-vue' // 导入 Search 图标组件
import { ElMessage } from 'element-plus'
import { ref } from 'vue'

const activeName = ref('signin')

// 登录按钮加载状态
const loading = ref(false)

// 是否开始倒计时
const isButtonDisabled = ref(false)
// 倒计时秒数
const countdown = ref(10)
// 用于存储倒计时的计时器
let timer: any = null

// 定义登录提交的对象
const loginModel = ref({
  code: '',
  username: 'admin',
  password: '123456',
  loginType: '',
  captchaId: '',
})

// 定义表单校验规则
const rules = ref({
  username: [
    {
      required: true,
      message: '请输入用户名',
      trigger: 'blur',
    },
  ],
  password: [
    {
      required: true,
      message: '请输入密码',
      trigger: 'blur',
    },
  ],
  code: [
    {
      required: true,
      message: '请输入验证码',
      trigger: 'blur',
    },
  ],
})

// 获取表单
const loginFormRef = ref()

// 图形验证码的base64数据
const captchaImage = ref('')
// 图形验证码的值
// let captchaCode = ''

// 是否自动提交授权确认(二维码登录自动提交)
const autoConsentKey: string = 'autoConsent'

/**
 * 处理点击事件的函数
 *
 * @param {TabsPaneContext} tab - 被点击的标签页对象，包含标签页的相关信息
 * @param {Event} event - 点击事件对象，包含事件的详细信息
 */
function handleClick(tab: TabsPaneContext, event: Event) {
  // 输出被点击的标签页对象和点击事件对象到控制台
  // eslint-disable-next-line no-console
  console.log(tab, event)
}

/**
 * 获取图形验证码
 */
function getCaptcha() {
  getImageCaptcha()
    .then((result: any) => {
      if (result.success) {
        captchaImage.value = result.data.imageData
        loginModel.value.captchaId = result.data.captchaId
      }
      else {
        ElMessage({
          message: result.message,
          type: 'warning',
        })
      }
    })
    .catch((e: any) => {
      ElMessage({
        message: `获取图形验证码失败：${e.message}`,
        type: 'warning',
      })
    })
}

/**
 * 获取短信验证码
 */
function getSmsCaptcha() {
  if (!loginModel.value.username) {
    ElMessage({
      message: '请先输入手机号.',
      type: 'warning',
    })
    return
  }
  getSmsCaptchaByPhone({ phone: loginModel.value.username })
    .then((result: any) => {
      if (result.success) {
        ElMessage({
          showClose: true,
          message: `获取短信验证码成功，固定为：${result.data}`,
          type: 'success',
        })
        isButtonDisabled.value = true
        // 重置倒计时
        countdown.value = 10
        // 开始倒计时
        startCountdown()
      }
      else {
        ElMessage({
          message: result.message,
          type: 'warning',
        })
      }
    })
    .catch((e: any) => {
      ElMessage({
        message: `获取短信验证码失败：${e.message}`,
        type: 'warning',
      })
    })
}

// 开始倒计时
function startCountdown() {
  timer = setInterval(() => {
    if (countdown.value > 0) {
      // 每秒减少 1
      countdown.value -= 1
    }
    else {
      // 倒计时结束，重置按钮
      resetButton()
    }
  }, 1000)
}

// 重置按钮
function resetButton() {
  isButtonDisabled.value = false
  // 清除计时器
  clearInterval(timer)
  timer = null
}

/**
 * 提交登录表单
 * @param type 登录类型，passwordLogin是密码模式，smsCaptcha短信登录
 */
function submitLogin(type: string) {
  // 动态调整校验规则
  adjustValidationRules(type)

  // 表单校验
  loginFormRef.value.validate().then((valid: boolean) => {
    if (valid) {
      loading.value = true
      loginModel.value.loginType = type
      loginSubmit(loginModel.value)
        .then((result: any) => {
          if (result.success) {
            // 移除自动提交缓存
            localStorage.removeItem(autoConsentKey)
            const target = getQueryString('target')
            if (target) {
              window.location.href = target
            }
            else {
              // 跳转到首页
              router.push({ path: '/' })
            }
          }
          else {
            ElMessage({
              message: result.message,
              type: 'warning',
            })
          }
        })
        .catch((e: any) => {
          ElMessage({
            message: `登录失败：${e.message}`,
            type: 'warning',
          })
        })
        .finally(() => {
          loading.value = false
        })
    }
    else {
      ElMessage({
        message: '表单校验失败,请填写必填项',
        type: 'warning',
      })
    }
  })
}

/**
 * 动态调整表单校验规则
 * @param type 登录类型
 */
function adjustValidationRules(type: string) {
  if (type === 'passwordLogin') {
    // 密码登录需要校验验证码
    rules.value.code = [
      {
        required: true,
        message: '请输入验证码',
        trigger: 'blur',
      },
    ]
  }
  else if (type === 'smsCaptcha') {
    // 短信登录不需要校验验证码
    rules.value.code = []
  }
}

/**
 * 根据类型发起OAuth2授权申请
 * @param type 三方OAuth2登录提供商类型
 */
function thirdLogin(type: string) {
  window.location.href = `${
    import.meta.env.VITE_OAUTH_ISSUER
  }/oauth2/authorization/${type}`
}

getCaptcha()
</script>

<template>
  <el-row>
    <el-col :span="24" class="login-container">
      <el-card class="login-card">
        <el-tabs v-model="activeName" @tab-click="handleClick">
          <el-tab-pane label="账号登录" name="signin">
            <el-form
              ref="loginFormRef"
              :model="loginModel"
              :rules="rules"
            >
              <el-form-item label="用户名" label-width="80px" prop="username">
                <el-input
                  v-model="loginModel.username"
                  placeholder="请输入用户名"
                  :prefix-icon="User"
                />
              </el-form-item>
              <el-form-item label="密码" label-width="80px" prop="password">
                <el-input
                  v-model="loginModel.password"
                  placeholder="请输入密码"
                  type="password"
                  show-password
                  :prefix-icon="Lock"
                />
              </el-form-item>
              <el-row>
                <el-col :span="16">
                  <el-form-item label="验证码" label-width="80px" prop="code">
                    <el-input
                      v-model="loginModel.code"
                      placeholder="请输入验证码"
                      :prefix-icon="Lock"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-image
                    :src="captchaImage"
                    alt="验证码"
                    class="captcha-image"
                    @click="getCaptcha"
                  />
                </el-col>
              </el-row>
              <el-form-item>
                <el-button
                  type="primary"
                  :loading="loading"
                  class="login-button"
                  @click="submitLogin('passwordLogin')"
                >
                  登录
                </el-button>
              </el-form-item>
            </el-form>
          </el-tab-pane>
          <el-tab-pane label="短信登录" name="signup">
            <el-form-item label="用户名" label-width="80px">
              <el-input
                v-model="loginModel.username"
                placeholder="请输入手机号 / 邮箱"
                :prefix-icon="User"
              />
            </el-form-item>
            <el-form-item label="授权码" label-width="80px">
              <el-input v-model="loginModel.password" placeholder="请输入授权码" :prefix-icon="Lock">
                <template #append>
                  <el-button :disabled="isButtonDisabled" @click="getSmsCaptcha">
                    {{ isButtonDisabled ? `请等待 ${countdown}s` : '获取授权码' }}
                  </el-button>
                </template>
              </el-input>
            </el-form-item>
            <el-form-item>
              <el-button
                type="primary"
                :loading="loading"
                class="login-button"
                @click="submitLogin('smsCaptcha')"
              >
                登录
              </el-button>
            </el-form-item>
          </el-tab-pane>
        </el-tabs>
        <el-divider content-position="center">
          其它登录方式
        </el-divider>
        <div class="other_login_icon">
          <img
            class="icon_item"
            style="width: 36px; height: 36px"
            src="@/assets/gitee.png"
            @click="thirdLogin('gitee')"
          >
          <img
            class="icon_item"
            style="width: 42px; height: 42px"
            src="@/assets/GitHub.png"
            @click="thirdLogin('github')"
          >
          <img
            class="icon_item"
            style="width: 42px; height: 42px"
            src="@/assets/wechat.png"
            @click="thirdLogin('wechat')"
          >
        </div>
      </el-card>
    </el-col>
  </el-row>
</template>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
}

.login-card {
  width: 600px;
}

.captcha-image {
  height: 32px;
  width: 100%;
  border: 1px solid #c0c4cc;
  border-radius: 5px;
  cursor: pointer;
}

.login-button {
  width: 100%;
}

.other_login_icon {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 0 10px;
  position: relative;
  margin-top: -5px;
}

.icon_item {
  margin-right: 10px;
  cursor: pointer;
}
</style>
